<?php
namespace Admin\Controller;

class ContractController extends \Admin\Controller\AdminController
{
	/**
	 * 合同列表
	 * @author 刘新
	 */
	public function contractList()
	{
		$con = I('condition');
		$where['status'] = array('egt', 0);
		
		if($con) {
			if(preg_match('/^[1-9]\d*$/', $con)) {
				$where['id'] = $con;
			} else if(preg_match('/^[\w]{2,}$/', $con)) {
				$where['code'] = $con;
			}
		}
		
		$list = $this->lists('Contract', $where);

		if($list) {
			foreach($list as $key => &$val) {
				$val['type_text'] = C('FUND_CONTRACT')[$val['type']];
			}
			int_to_string($list);
		}
		$this->assign('_list', $list);
		$this->display('list');
	}
	
	/**
	 * 添加合同
	 * @author 刘新
	 */
	public function addContract()
	{
		if(IS_GET) {
			$this->assign('_title', '新增合同');
			$this->display('add_edit');
		}
		
		//添加合同
		$res = D('Contract')->addContract();
		if($res['error'] != 0) $this->error($res['msg']);
		$this->success('添加成功', U('Contract/contractList'));
	}
	
	/**
	 * 编辑合同
	 * @author 刘新
	 */
	public function editContract()
	{
		$id = I('id', '', '/^[1-9]\d*$/');
		!$id && $this->error('请选择要编辑的合同');
		
		if(IS_GET) {
			$contract = M('Contract')->where(array('id' => $id))->find();
			!$contract && $this->error('合同信息查询失败');
			$this->assign('contract', $contract);
			$this->assign('_title', '编辑合同');
			$this->display('add_edit');
		}
	
		//编辑合同
		$res = D('Contract')->editContract();
		if($res['error'] != 0) $this->error($res['msg']);
		$this->success('添加成功', U('Contract/contractList'));
	}

	/**
	 * 编辑合同
	 * @author 刘新
	 */
	public function contractDetail()
	{
		$id = I('id', '', '/^[1-9]\d*$/');
		!$id && $this->error('参数错误');
		
		//查询详情
		$contract = M('Contract')->where(array('id' => $id))->find();
		!$contract && $this->error('合同信息查询失败');
		$contract['type_text'] = C('FUND_CONTRACT')[$contract['type']];
		$contract = array($contract);
		int_to_string($contract);
		int_to_string($contract, array('type' => array(0 => '基金合同')));
		
		//查询合同日志
		$contractLog = M('ContractLog')->where(array('contract_id' => $id))->order('update_time desc')->select();
		!$contractLog && $this->error('合同日志信息查询失败');

		$this->assign('log', $contractLog);
		$this->assign('contract', $contract[0]);
		$this->assign('_title', '合同详情');
		$this->display('detail');
	}
	
	/**
	 * 合同状态修改
	 * @author 刘新
	 */
	public function changeStatus($method=null)
	{
		$id = array_unique((array)I('id',0));
		$id = is_array($id) ? implode(',',$id) : $id;
		if ( empty($id) ) $this->error('请选择要操作的数据!');
		$map['uid'] =   array('in',$id);
	
		switch ( strtolower($method) )
		{
			case 'forbid':
				$this->forbid('Contract', $map );
				break;
			case 'resume':
				$this->resume('Contract', $map );
				break;
			case 'delete':
				$this->delete('Contract', $map );
				break;
			default:
				$this->error('参数非法');
		}
	}
}